package leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-01-26 15:52
 **/
public class LeetCode2013 {

    Map<Integer, Map<Integer, Integer>> map;

    public LeetCode2013() {
        map = new HashMap<>();
    }

    public void add(int[] point) {
        int x = point[0];
        int y = point[1];
        map.putIfAbsent(y, new HashMap<>());
        Map<Integer, Integer> t = this.map.get(y);
        t.put(point[0], t.getOrDefault(point[0], 0) + 1);
    }

    public int count(int[] point) {
        int res = 0;
        int x = point[0];
        int y = point[1];
        //如果没有和当前坐标在同一垂直线上的点,直接返回0
        if (!map.containsKey(y)) {
            return 0;
        }
        Map<Integer, Integer> yCnt = this.map.get(y);
        for (Map.Entry<Integer, Map<Integer, Integer>> entry : this.map.entrySet()) {
            int col = entry.getKey();
            //纵坐标为col的(横坐标:个数)
            Map<Integer, Integer> colCnt = entry.getValue();
            if (col != y) {
                //边长,根据对称性，这里可以不用取绝对值
                int d = col - y;
                //构成正方形的个数相当于其它三个点的乘积
                res += colCnt.getOrDefault(x, 0) * yCnt.getOrDefault(x - d, 0) * colCnt.getOrDefault(x - d, 0);
                res += colCnt.getOrDefault(x, 0) * yCnt.getOrDefault(x + d, 0) * colCnt.getOrDefault(x + d, 0);
            }
        }
        return res;
    }

}
